package com.yenroc.invoice.util;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.utils.PdfMerger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.util.List;

public class FileUtil {
    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

    /**
     * 将给定List集合中的pdf文档, 按照顺序依次合并, 生成最终的目标PDF文档
     *
     * @param pdfPathLists 待合并的PDF文档路径集合, 可以是本地PDF文档, 也可以是网络上的PDF文档
     * @param destPath     目标合并生成的PDF文档路径
     */
    public static boolean mergeMultiplePdfs(List<String> pdfPathLists, String destPath) {
        try {
            int size = pdfPathLists.size();
            byte[] pdfData = getPdfBytes(pdfPathLists.get(0));
            for (int i = 1; i < size; i++) {
                pdfData = mergePdfBytes(pdfData, getPdfBytes(pdfPathLists.get(i)));
            }
            if (pdfData != null) {
                FileOutputStream fis = new FileOutputStream(destPath);
                fis.write(pdfData);
                fis.close();
            }
            return true;
        } catch (Exception e) {
            logger.error("合并PDF异常:", e);
        }
        return false;
    }

    /**
     * 基于内存中的字节数组进行PDF文档的合并
     *
     * @param firstPdf  第一个PDF文档
     * @param secondPdf 第二个PDF文档
     */
    private static byte[] mergePdfBytes(byte[] firstPdf, byte[] secondPdf) throws IOException {
        if (firstPdf != null && secondPdf != null) {
            // 创建字节数组, 基于内存进行合并
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PdfDocument destDoc = new PdfDocument(new PdfWriter(baos));
            // 合并的pdf文件对象
            PdfDocument firstDoc = new PdfDocument(new PdfReader(new ByteArrayInputStream(firstPdf)));
            PdfDocument secondDoc = new PdfDocument(new PdfReader(new ByteArrayInputStream(secondPdf)));
            // 合并对象
            PdfMerger merger = new PdfMerger(destDoc);
            merger.merge(firstDoc, 1, firstDoc.getNumberOfPages());
            merger.merge(secondDoc, 1, secondDoc.getNumberOfPages());
            // 关闭文档流
            merger.close();
            firstDoc.close();
            secondDoc.close();
            destDoc.close();
            return baos.toByteArray();
        }
        return null;
    }

    /**
     * 将pdf文档转换成字节数组
     *
     * @param pdf PDF文档路径
     * @return 返回对应PDF文档的字节数组
     */
    private static byte[] getPdfBytes(String pdf) throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        InputStream is;
        if (pdf.startsWith("http://") || pdf.startsWith("https://")) {
            is = new URL(pdf).openStream();
        } else {
            is = new FileInputStream(pdf);
        }
        byte[] data = new byte[2048];
        int len;
        while ((len = is.read(data)) != -1) {
            out.write(data, 0, len);
        }
        return out.toByteArray();
    }

}